package com.dsjy.yf.address.controller;

import com.dsjy.yf.address.security.common.api.CommonResult;
import com.dsjy.yf.address.security.model.dto.UserDTO;
import com.dsjy.yf.address.security.service.JwtAuthService;
import com.dsjy.yf.address.security.utils.CommonResultUtil;
import com.dsjy.yf.address.security.utils.EncryptUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;



import java.util.Collection;
import java.util.HashMap;

/**
 * @author Ken
 * @date 2020/11/5 上午 09:40
 */
@RestController
@ResponseBody
@RequestMapping("/auth")
@CrossOrigin(origins = "*", originPatterns = "true")
public class AuthController {

    @Autowired
    JwtAuthService jwtAuthService;

    @GetMapping("/userinfo")
    public CommonResult<Collection<? extends GrantedAuthority>> getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        return CommonResultUtil.success(authorities);
    }

    /**
     * 模拟登陆
     */
    @PostMapping("/login")
    public CommonResult<HashMap<String, String>> login(@RequestBody UserDTO userDTO) {
        String password = userDTO.getPassword();
        if (password != null) {
            password = EncryptUtils.aesDecrypt(password);
        }
        return jwtAuthService.login(userDTO.getUsername(), password);
    }

}
